package com.cy.shiro;

import com.alibaba.fastjson.JSONObject;
import com.cy.config.EnumConst;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 权限拦截器
 */
public class PermissionFilter extends AuthorizationFilter {

    /**
     * 排除不需要过滤权限的URL（带请求方式）
     */
    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object requestMethod) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        if (requestMethod == null){
            return super.onPreHandle(request, response, requestMethod);
        }
        String currentMethod = req.getMethod();
        String[] rms = (String[]) requestMethod;
        for (String rm : rms){
            if (currentMethod.equalsIgnoreCase(rm))
                return true;
        }
        return super.onPreHandle(request, response, requestMethod);
    }

    /**
     * 验证权限
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        String requestURI = req.getRequestURI();
        String contextPath = req.getContextPath();
        if (!"/".equals(contextPath)){
            requestURI = requestURI.substring(contextPath.length());
        }

        String requestMethod = req.getMethod();
        Subject subject = getSubject(request, response);
        boolean isAllowed = subject.isPermitted(requestURI +":"+ requestMethod);
        System.out.println("current request url is "+ (isAllowed ? "allowed" : "denied") +": "+ requestURI +"("+requestMethod+")");
        return isAllowed;
    }

    /**
     * 拒绝访问跳转
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String requestType = req.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(requestType)){//AJAX请求
            Map<String, Object> result = new HashMap<>();
            result.put("status", EnumConst.RetCode.NO_PERMISSION.getCode());
            result.put("msg", EnumConst.RetCode.NO_PERMISSION.getValue());
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.write(JSONObject.toJSONString(result));
            return false;
        }
        return super.onAccessDenied(request, response);
    }
}